<?php

namespace App\Models\Mental;

use App\Models\BasicModel;
use App\Models\User;
use App\Models\Users\MoneyLog;
use Dcat\Admin\Traits\HasDateTimeFormatter;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\DB;
use Jiannei\Response\Laravel\Support\Facades\Response;

class Lists extends BasicModel
{
	use HasDateTimeFormatter;
    use SoftDeletes;
    protected $table = 'mental_lists';


    public function start($uid,$test_id){
        $test= self::find($test_id);
        if($test->price>0){
           $data=[
                'user_id'=>$uid,
                'list_id'=>$test_id,
                'price'=>$test->price,
            ];
        }else{
            $data=[
                'user_id'=>$uid,
                'list_id'=>$test_id,
                'price'=>$test->price,
                'pay'=>1,
            ];
        }
        return Logs::create($data);
    }

    public function end($uid,$log_id,$score){
        $log=Logs::where(['id'=>$log_id,'user_id'=>$uid])->first();
        $result=Results::where('score_begin','<=',$score)->where('score_end','>=',$score)
            ->where(['list_id'=>$log->list_id])->first();
        $log->finished=1;
        $log->score=$score;
        $log->result=$result->content ?? '未找到测试结果';
        $log->save();
        return $result;
    }
    /**
     * @throws \Exception
     */
    public function pay($uid, $oid): void
    {
        $order=Logs::find($oid);
        if($order->pay==0){
            $user=User::query()->find($uid);
            if($user->money<$order->price){
               throw new \Exception('余额不足');
            }
            (new MoneyLog())->add($uid,-$order->price,'心理测试');
            $order->pay=1;
            $order->save();
        }
    }

    public function type()
    {
        return $this->belongsTo(Type::class, 'type_id', 'id');
    }
}
